package com.ziyun.erp.modules.promotion.service.impl;

import com.cloud.bus.core.EventBusPusher;
import com.cloud.bus.event.cart.SendCouponEvent;
import com.ziyun.erp.modules.member.service.UserBaseInfoService;
import com.ziyun.erp.modules.promotion.service.SendCouponService;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author jiangli
 * @date 2018-09-20 15:25
 */
@Service("sendCouponService")
public class SendCouponServiceImpl implements SendCouponService {

    @Autowired
    private UserBaseInfoService userBaseInfoService;

    @Override
    public R doBatchSendCoupon(String sendCouponType, String couponIds, String param , String quantity, String remarks) {
        Set<String> sendCouponParam=new HashSet<>();
        if ("userIds".equals(sendCouponType)) {
            Map<String, Object> map = new HashMap<>();
            param = param.replaceAll(" ", "").replaceAll("，", ",").trim();
            List<String> userIds = Arrays.asList(param.split(","));
            //判断填写的会员ID是否正确
            Integer count = userBaseInfoService.getCountByIds(param.split(","));
            if (count != userIds.size()) {
                return R.error("存在无效会员ID,请修改!");
            }

            Set<Integer> userIdSet = new HashSet<>();
            for (String userId : userIds) {
                userIdSet.add(Integer.valueOf(userId));
            }

            for (Integer integer : userIdSet) {
                sendCouponParam.add(String.valueOf(integer));
            }
        }else{

            List<String> parmaList = Arrays.asList(param.split(","));
            sendCouponParam =  new HashSet<>(parmaList);
        }

        SendCouponEvent event = SendCouponEvent.builder().source(this).couponIds(couponIds).sendCouponType(sendCouponType).sendCouponParam(sendCouponParam).sendCouponSource("giveout")
                                .quantity(Integer.valueOf(quantity)).remarks(remarks).build();

        EventBusPusher.syncPost(event);

        return R.ok();
    }
}
